﻿using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using mojoPortal.Web;
using Resources;
using mojoPortal.Web.Framework;
using System.Collections;
using mojoPortal.Business;
using System.Linq;
using Telerik.Web.UI;
using ud_gSDMS.Code_Service;

namespace ud_gSDMS.timesheet
{
    public partial class Report : mojoBasePage
    {
        private int pageId = -1;
        private int moduleId = -1;

        void Page_Load(object sender, EventArgs e)
        {
            if (SiteUtils.GetCurrentSiteUser()==null)
            {
                WebUtils.SetupRedirect(this, SiteRoot + "/AccessDenied.aspx");
            }
            else
            {
                if (!Page.IsPostBack)
                {
                    PopulateLabels();
                    PopulateControls();
                }  
            }
        }
        /// <summary>
        /// Xuất dữ liệu từ GridView ra Excel
        /// </summary>
        private void XuatDuLieuRaXMLExcel()
        {
            //Tao report tu DataTable chay ok nhung ko hoan hao theo y nguoi dung
            DataTable tb = data;
            data.TableName = "TimeSheet";
            data.WriteXml(Server.MapPath(".") + @"\ExportTimeSheet.xls", XmlWriteMode.IgnoreSchema);
            Response.Redirect("ExportTimeSheet.xls");
        }

        protected void btnExportExcel_Click(object sender, EventArgs e)
        {
            //XuatDuLieuRaXMLExcel();
            var db = ViewState["listReportTimSheet"];
            if (db != null)
            {
                hiddenGrid.DataSource = db;
                hiddenGrid.DataBind();
                var name = ("TimeSheet-Report-" + DateTime.Now.ToShortDateString().Replace("/", "").Replace(":", "").Replace(" ", "_"));
                hiddenGrid.ExportSettings.FileName = name;
                hiddenGrid.ExportSettings.IgnorePaging = true;
                hiddenGrid.ExportSettings.OpenInNewWindow = true;
                hiddenGrid.MasterTableView.ExportToExcel();
            }
        }
        private void PopulateLabels()
        {

        }
        private void PopulateControls()
        {
            datTimeReport_Date_from.SelectedDate = DateTime.Now.AddMonths(-2);
            datTimeReport_Date_to.SelectedDate = DateTime.Now;
            datTimeReport_Date_from.MaxDate = DateTime.Now;
            datTimeReport_Date_to.MaxDate = DateTime.Now;
            LoadControl();
            LoadGrid();

        }
        public override void VerifyRenderingInServerForm(Control control)
        {
            //Xác nhận điều khiển HtmlForm tại thời gian chạy ASP.NET
        }

        private static DataTable data;
        private void LoadGrid()
        {
            float totalHours = 0;
            float totalDays = 0;
            float totalMonths = 0;
            if (cboReportStatus.SelectedValue == "2")
            {
                cboReportStatus.Text = "Approved";
            }
            // //cboAccount.Text.Trim() == "" ? null : cboAccount.SelectedValue,
            data = gSDMS_BL.ud_gSDMS_TIMESHEET_SearchReport(datTimeReport_Date_from.SelectedDate == null ? null : datTimeReport_Date_from.SelectedDate.Value.ToShortDateString(),
                                                         datTimeReport_Date_to.SelectedDate == null ? null : datTimeReport_Date_to.SelectedDate.Value.ToShortDateString(),
                                                         cboReportAccount.Text.Trim() == "" ? null : cboReportAccount.SelectedValue,
                                                         cboReportProject.Text.Trim() == "" ? null : cboReportProject.SelectedValue,
                                                         cboReportStatus.Text.Trim() == "" ? null : cboReportStatus.SelectedValue,
                                                         cboLeader.SelectedValue);

            if (ViewState["SortExpression"] != null)
            {
                var dv = data.DefaultView;
                dv.Sort = ViewState["SortExpression"].ToString();
                data = dv.Table;
            }
            grdTimeSheet.DataSource = data;
            grdTimeSheet.DataBind();
            ViewState["listReportTimSheet"] = data;
            if (grdTimeSheet.Rows.Count > 0)
            {
                int i = grdTimeSheet.Rows.Count;
                for (int j = 0; j < i; j++)
                {
                    //totalHours = totalHours + float.Parse(grdTimeSheet.Rows[j].Cells[7].Text);
                    totalHours = totalHours + float.Parse(data.Rows[j]["Hours"].ToString());
                    // totalDays = Convert.ToDouble(Math.Round((totalHours/8),2));
                }
            }
            txtTotalHours.Text = totalHours.ToString();// +" Hours";
            txtTotalDays.Text = (Math.Round(totalHours / 8, 2)).ToString();// +" Day";
            txtTotalMonths.Text = Math.Round(totalHours /(8*24), 2).ToString();// +" Month";
        }

        private void LoadControl()
        {
            var db = new gSDMS_DataLinq();
            cboReportStatus.Items.Add(new RadComboBoxItem("",""));
            DataTable tbStatus = Library.LINQToDataTable(db, db.ud_gSDMS_CAT_TIMESHEET_STATUS);
            for (int i = 0; i < tbStatus.Rows.Count; i++)
            {
                cboReportStatus.Items.Add(new RadComboBoxItem(tbStatus.Rows[i]["Name"].ToString(), tbStatus.Rows[i]["CAT_TimeSheet_Status_ID"].ToString()));
            }


            cboReportAccount.DataValueField = "UserID";
            cboReportAccount.DataTextField = "LoginName";
            cboReportAccount.DataSource = gSDMS_BL.ud_gSDMS_TIMESHEET_User_Lst();
            cboReportAccount.DataBind();
            cboReportAccount.Items.Insert(0, new RadComboBoxItem("", ""));
            cboReportAccount.SelectedValue = "";

            DataTable tbPro = Library.LINQToDataTable(db, db.ud_gSDMS_PROJECTs);
            cboReportProject.Items.Add(new RadComboBoxItem("",""));
            for (int i = 0; i < tbPro.Rows.Count; i++)
            {
                cboReportProject.Items.Add(new RadComboBoxItem(tbPro.Rows[i]["Code"].ToString(),tbPro.Rows[i]["Project_ID"].ToString()));
            }
            cboReportProject.SelectedValue = "";

            cboReportStatus.SelectedIndex = 2;

            cboLeader.DataSource = gSDMS_BL.ud_gSDMS_PROJECT_Leader_Tab();
            cboLeader.DataValueField = "UserID";
            cboLeader.DataTextField = "LoginName";
            cboLeader.DataBind();
            cboLeader.Items.Insert(0, new RadComboBoxItem("", ""));
            cboLeader.SelectedValue = "";
        }

        private void grdTimeSheet_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grdTimeSheet.PageIndex = e.NewPageIndex;
            LoadGrid();
        }
        private void grdTimeSheet_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "delete")
            {
                gSDMS_BL.ud_gSDMS_TIMESHEET_Del(e.CommandArgument.ToString(), true);
            }
        }
        void grdTimeSheet_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            LoadGrid();
        }
        //ham su ly su kien selectedindexchange
        public void itemSelected(object sender,EventArgs e)
        {
            if (string.IsNullOrEmpty(cboReportProject.Text) == true)
            {
                cboReportAccount.Items.Clear();
                cboReportAccount.DataValueField = "UserID";
                cboReportAccount.DataTextField = "LoginName";
                cboReportAccount.DataSource = gSDMS_BL.ud_gSDMS_TIMESHEET_User_Lst();
                cboReportAccount.DataBind();
                cboReportAccount.Items.Insert(0, new RadComboBoxItem("", ""));
                cboReportAccount.SelectedValue = "";
                
                return;
            }
            else
            {
                cboReportAccount.Items.Clear();
                DataTable tb = gSDMS_BL.getListAccountID(cboReportProject.Items[cboReportProject.SelectedIndex].Value);
                cboReportAccount.Items.Add(new RadComboBoxItem("", ""));
                for (int i = 0; i < tb.Rows.Count; i++)
                {
                    cboReportAccount.Items.Add(new RadComboBoxItem(tb.Rows[i]["LoginName"].ToString(), tb.Rows[i]["UserID"].ToString()));
                }
                cboReportAccount.SelectedValue = "";
            }
        }
        void grdTimeSheet_Sorting(object sender, GridViewSortEventArgs e)
        {
            if (ViewState["Direction"] == null) ViewState["Direction"] = " DESC";
            else if (ViewState["Direction"].ToString() == " ASC") ViewState["Direction"] = " DESC";
            else if (ViewState["Direction"].ToString() == " DESC") ViewState["Direction"] = " ASC";
            grdTimeSheet.EditIndex = -1;
            string strSortExp = e.SortExpression + ViewState["Direction"].ToString();
            ViewState["SortExpression"] = strSortExp;

            LoadGrid();
        }

        void btnReportSearch_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            LoadGrid();
        }

        #region OnInit

        protected override void OnPreInit(EventArgs e)
        {
            AllowSkinOverride = true;
            base.OnPreInit(e);
            Load += Page_Load;
        }

        protected override void OnInit(EventArgs e)
        {
            LoadParams();
            LoadPanels();
            base.OnInit(e);
            grdTimeSheet.PageIndexChanging += grdTimeSheet_PageIndexChanging;
            grdTimeSheet.RowCommand += grdTimeSheet_RowCommand;
            grdTimeSheet.RowDeleting += grdTimeSheet_RowDeleting;
            grdTimeSheet.Sorting += grdTimeSheet_Sorting;
            btnExportExcel.Click += btnExportExcel_Click;
            //btnExportExcel.Click += new EventHandler(btnExportExcel_Click);
            btnReportSearch.Click += btnReportSearch_Click;

            //btnFinish.Click += btnFinish_Click;
            SuppressPageMenu();
        }

        //void btnFinish_Click(object sender, EventArgs e)
        //{
        //    WebUtils.SetupRedirect(this, SiteUtils.GetCurrentPageUrl());
        //}

        private void LoadParams()
        {
            pageId = WebUtils.ParseInt32FromQueryString("pageid", pageId);
            moduleId = WebUtils.ParseInt32FromQueryString("mid", true, moduleId);
        }

        private void LoadPanels()
        {
            Hashtable settings = ModuleSettings.GetModuleSettings(moduleId);
            //config = new ContactFormConfiguration(settings);
            bool showLeftColumnAdmin = ConfigHelper.GetBoolProperty("ShowLeftColumnAdmin", false);
            bool showRightColumnAdmin = ConfigHelper.GetBoolProperty("ShowRightColumnAdmin", false);
            bool showTopColumnAdmin = ConfigHelper.GetBoolProperty("ShowTopColumnAdmin", false);
            bool showBottomColumnAdmin = ConfigHelper.GetBoolProperty("ShowBottomColumnAdmin", false);
            int showCenterColumnAdmin = ConfigHelper.GetIntProperty("ShowCenterColumnAdmin", 0);
            LoadSideContent(showLeftColumnAdmin, showRightColumnAdmin, showTopColumnAdmin, showBottomColumnAdmin, showCenterColumnAdmin);
        }
        #endregion
    }
}